const express = require('express')
const router = express.Router()

const Profile = require('../../model/profile.js')

// 验证token
const passport = require('passport')


router.get('/test', (req, res) => {
    res.send('kjdshfjk')
})


// @route post api/profiles/add 
// @desc  创建信息接口
// @access Private
router.post('/add', passport.authenticate("jwt", { session: false }), (req, res) => {
    const profileFields = {}

    if (req.body.type) profileFields.type = req.body.type
    if (req.body.describe) profileFields.describe = req.body.describe
    if (req.body.input) profileFields.input = req.body.input
    if (req.body.output) profileFields.output = req.body.output
    if (req.body.cash) profileFields.cash = req.body.cash
    if (req.body.remark) profileFields.remark = req.body.remark

    new Profile(profileFields).save().then(p => {
        res.json({ data: { p }, status: 200, message: "ok" })
    })
})


// @route get api/profiles 
// @desc  获取所有信息
// @access Private

router.get('/', passport.authenticate("jwt", { session: false }), async(req, res) => {
    try {
        const infos = await Profile.find()
        if (!infos) {
            return res.status(404).json('没有任何内容')
        }
        res.json({ data: { infos }, status: 200 })
    } catch (err) {
        res.status(404).json(err)
    }
})

// @route get api/profiles 
// @desc  获取单个信息
// @access Private

router.get('/:id', passport.authenticate("jwt", { session: false }), async(req, res) => {
    try {
        const info = await Profile.findOne({ _id: req.params.id })
        if (!info) {
            return res.status(404).json('没有任何内容')
        }
        res.json(info)
    } catch (err) {
        res.status(404).json(err)
    }
})

// @route get api/profiles/edit 
// @desc  编辑信息接口
// @access Private
router.post('/edit/:id', passport.authenticate("jwt", { session: false }), async(req, res) => {
    const profileFields = {}

    if (req.body.type) profileFields.type = req.body.type
    if (req.body.describe) profileFields.describe = req.body.describe
    if (req.body.input) profileFields.input = req.body.input
    if (req.body.output) profileFields.output = req.body.output
    if (req.body.cash) profileFields.cash = req.body.cash
    if (req.body.remark) profileFields.remark = req.body.remark

    const info = await Profile.findOneAndUpdate({ _id: req.params.id }, { $set: profileFields }, { new: true })
    if (info) {
        res.json({ data: { info }, status: 200 })
    }
})

// @route get api/profiles/delete
// @desc  删除信息接口
// @access Private

router.delete('/delete/:id', passport.authenticate("jwt", { session: false }), async(req, res) => {
    try {
        await Profile.findOneAndDelete({ _id: req.params.id })
        res.json({ message: "ok", status: 200 })

    } catch (err) {
        res.status(404).json(err)
    }
})

module.exports = router